import org.gdal.gdal.Band;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.Driver;
import org.gdal.gdal.gdal;
import org.gdal.gdalconst.gdalconst;
import org.gdal.gdalconst.gdalconstConstants;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import utilityTools.ShpReaderUtil;

import java.io.File;
import java.io.FileNotFoundException;

public class GDALOperation {
    static {
        //不注册的话，后续接口无法使用
        gdal.AllRegister();
    }

    public void getRasterGeoTransform() {
        String srcNIRPath = "E:\\9.1GISData\\idwTest\\raster7.tif";
        String path1 = "E:\\9.1GISData\\idwTest\\LE71420422003150ASN00_B1.TIF";
        String pathDemo = "E:\\vectorOutput\\rasterDemo2.tif";
        Dataset dsRaster = gdal.Open(srcNIRPath, gdalconstConstants.GA_ReadOnly);
        double[] srcGeoTF = dsRaster.GetGeoTransform();
        for (double v : srcGeoTF) {
            System.out.print(v + " ");
        }
        System.out.print(System.lineSeparator());
        Dataset dsDemo = gdal.Open(path1, gdalconstConstants.GA_ReadOnly);
        double[] geotfDemo = dsDemo.GetGeoTransform();
        for (double value : geotfDemo) {
            System.out.print(value + " ");
        }
    }

    public void getRasterMetadata() throws Exception {
        String srcNIRPath = "E:\\9.1GISData\\idwTest\\raster7.tif";
        String path1 = "E:\\9.1GISData\\idwTest\\LE71420422003150ASN00_B1.TIF";
        String pathDemo = "E:\\vectorOutput\\rasterDemo2.tif";
        Dataset dsRaster = gdal.Open(pathDemo, gdalconstConstants.GA_ReadOnly);
        double[] geoTF = dsRaster.GetGeoTransform();
        double minX = geoTF[0];
        System.out.println("X最小值：" + minX);
        double maxY = geoTF[3];
        System.out.println("Y最大值:" + maxY);
        double pixcelSize = geoTF[1];
        System.out.println("像元大小：" + pixcelSize);
        int xCount = dsRaster.GetRasterXSize();
        int yCount = dsRaster.getRasterYSize();
        double maxX = minX + pixcelSize * xCount;
        System.out.println("X最大值是：" + maxX);
        double minY = maxY - pixcelSize * yCount;
        System.out.println("Y的最小值：" + minY);
        System.out.println(dsRaster.GetProjection());
//        Hashtable metas= dsRaster.GetMetadata_Dict();
//        System.out.println("键值对的个数："+metas.entrySet().size());
//        Set<Map.Entry> tmp= metas.entrySet();
//        for (Map.Entry entry : tmp) {
//            System.out.println("[key:"+entry.getKey()+", value:"+entry.getValue()+"]");
//        }
//        System.out.println("坐标系参数:");
//        CoordinateReferenceSystem crs84 = CRS.decode("EPSG:3857");
//        System.out.println(crs84.toWKT());
    }

    double kilometre = 0.0089932202929999989d;//1千米转为度
    Dataset rasterDs = null;//插值后的栅格结果

    public void testCreateRaster() throws Exception {
        String rn = "demoRaster";
        double pixelSizeM = 200;
        String pathShp = "E:\\9.1GISData\\idwTest\\countcenterofshanxi.shp";
        SimpleFeatureSource sfs = ShpReaderUtil.getShpfileSource(new File(pathShp), "UTF-8");
        createRasterDataset(rn, pixelSizeM, sfs.getBounds());
    }

    private void createRasterDataset(String nameRaster, double pixelSize, ReferencedEnvelope srcEnvelope) throws Exception {
        double srcHeight = srcEnvelope.getHeight();
        double srcWidth = srcEnvelope.getWidth();
        //仿射变换的6参数：2个是坐标参数，两个是像元大小，两个是正北方向
        String pathRaster = createNewFile(nameRaster, ".tif");
        //把度转换为m
        double mWidth = srcWidth / kilometre * 1000;
        double mHeight = srcHeight / kilometre * 1000;
        int xCount = (int) Math.floor(mWidth / pixelSize);
        int yCount = (int) Math.floor(mHeight / pixelSize);
        double calcPixel = pixelSize * (kilometre / 1000);
        double[] geoTransForm = {srcEnvelope.getMinX(), calcPixel, 0.0, srcEnvelope.getMaxY(), 0.0, -calcPixel};
        String rasterProject = CRS.decode("EPSG:4326").toWKT();
        Driver driverRaster = gdal.GetDriverByName("GTiff");
        Dataset dstDs = driverRaster.Create(pathRaster, xCount, yCount, 1, gdalconst.GDT_Float32);
        //栅格图像的地理范围和位置
        dstDs.SetGeoTransform(geoTransForm);
        dstDs.SetProjection(rasterProject);//暂时先使用wgs84的坐标系
        rasterDs = dstDs;
        System.out.println("执行成功.");
    }

    //在默认工作空间创建不重名的指定扩展名的文件
    private String createNewFile(String nameNoExtent, String strExtent) throws FileNotFoundException {
        String pathExcel = "E:\\9.1GISData\\idwTest\\" + nameNoExtent + strExtent;
        File file = new File(pathExcel);
        if (file.exists()) {
            return createNewFile(nameNoExtent + "_1", strExtent);
        }
        return pathExcel;
    }

}
